package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplateIhuyi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.CountsUserVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import com.tanhua.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplateIhuyi smsTemplateIhuyi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    /**
     * 发送验证码
     * @param phone
     */
    public void sendSms(String phone) {

        //int mobile_code = (int)((Math.random()*9+1)*100000);
        //String code = String.valueOf(mobile_code);
        String code = "123456";
        //smsTemplateIhuyi.sendSms(phone);
        //存入redis缓存中
        redisTemplate.opsForValue().set(Constants.CAP_CODE+phone,code, Duration.ofMinutes(5));
    }

    /**
     * 用户登录-登录校验
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
        //1. 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + phone);
        //2.判断验证码是否正确
        if (StringUtils.isEmpty(code) || !code.equals(redisCode)){
            //验证码有误
            throw new RuntimeException("验证码校验失败");
        }

        //比对成功后,删除redis中的验证码
        redisTemplate.delete(Constants.CAP_CODE+phone);

        //3.验证码正确获取用户
        User user = userApi.findByMobile(phone);

        boolean isNew = false;

        //判断用户是否存在
        if (user == null){
            //用户不存在添加新用户
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            user.setCreated(new Date());
            user.setUpdated(new Date());
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;

            //注册环信账号
            String hxUser = "hx" + user.getId();
            Boolean aBoolean = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (aBoolean){
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                //调用API修改数据
                userApi.update(user);
            }
        }

        //登录成功生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(tokenMap);

        //返回结果
        Map resMap = new HashMap();
        resMap.put("token",token);
        resMap.put("isNew",isNew);

        return resMap;
    }

    /**
     * 修改手机号-校验验证码
     * @param code
     * @param mobile
     * @return
     */
    public boolean checkVerificationCode(String code, String mobile) {
        //从redis里获取验证码
        String redisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + mobile);

        return !StringUtils.isEmpty(code) && code.equals(redisCode);
    }

    /**
     * 修改手机号 - 3 保存
     * @param phone
     */
    public void updateNewPhone(String phone) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();

        User user = new User();
        user.setMobile(phone);
        user.setId(userId);

        userApi.updateNewPhone(user);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     * @return
     */
    public CountsUserVo counts() {
        Long userId = UserHolder.getUserId();
        //查询redis中自己喜欢的用户总数
        Long loveCount = redisTemplate.opsForSet().size(Constants.USER_LIKE_KEY + userId);
        //调用API查询粉丝的总数
        Integer fanCount = userLikeApi.countsFans(userId);
        //调用API查询互相喜欢的总数
        Integer eachLove = userLikeApi.countsEachLove(userId);

        CountsUserVo vo = new CountsUserVo();
        vo.setFanCount(fanCount);
        vo.setLoveCount(Math.toIntExact(loveCount));
        vo.setEachLoveCount(eachLove);
        return vo;
    }
}
